<?php
header("Content-Type:application/json;charset=utf-8");
header("Access-Control-Allow-Origin:*");
if($_SERVER["REQUEST_METHOD"]=="POST"){
    //1.准备链接数据库的配置信息
    $host="127.0.0.1";
    $name="root";
    $pwd="";
    $port="3306";
    $db="mia";
    //2.创建链接
    $conn=new mysqli($host,$name,$pwd,$db,$port);
    //3.设置链接字符集
    mysqli_query($conn,"SET NAMES UTF8");

//    [gId] => 1
//    [gName] => 长大我最棒系列全套8册
//    [gDes] => 宝宝培养高情商绘本
//    [gNewPrice] => 59.00
//    [gOldPrice] => 78.40
//    [gImg] => ./images/rec_01.jpg
//    [uId] => 1

    $query = " SELECT *FROM `carts` WHERE `uId`='" . $_POST["uId"] . "' AND `gId`='" . $_POST["gId"] . "'";

    $resultA = $conn->query($query);
    if($resultA->num_rows>=1){
        $update = " UPDATE `carts` SET num=num+" . $_POST["num"] . ", gTotal=num*gNewPrice WHERE `uId`='" . $_POST["uId"] . "' AND `gId`='" . $_POST["gId"] . "'";
        $resultB=$conn->query($update);
        if($resultB){
            print_r(json_encode(array("msg"=>"加入成功","status" => 1)));
        }else{
            print_r(json_encode(array("msg"=>"加入失败", "status" => -1)));
        }
    }else{
        $insert="INSERT INTO `carts` (`gId`,`gName`,`gNewPrice`,`gOldPrice`,`gImg`,`gDes`,`gTotal`,`num`,`gSize`,`uId`) VALUES('".$_POST["gId"]."','".$_POST["gName"]."','".$_POST["gNewPrice"]."','".$_POST["gOldPrice"]."','".$_POST["gImg"]."','".$_POST["gDes"]."','".$_POST["num"]*$_POST["gNewPrice"]."','".$_POST["num"]."','".$_POST["gSize"]."','".$_POST["uId"]."')";
        $resultC = $conn->query($insert);
        if($resultC) {
            print_r(json_encode(array("msg" => "加入成功", "status" => 2)));
        } else {
            print_r(json_encode(array("msg" => "加入失败", "status" => -2)));
        }
    }
}